<template>
  <div v-if="show" class="component-autoupdate flash animate__animated animate__fast" :class="{ 'animate__bounceOutDown': showOut, 'animate__bounceInUp': !showOut, 'over': over }">
    <el-button v-if="!over" type="success" class="btn" size="small" @click="onHidden">{{ lang.t('components.autoupdate.btn') }}</el-button>
    <el-button v-else class="btn" size="small" @click="onReboot" text bg>{{ lang.t('components.autoupdate.reboot') }}</el-button>
    <div class="version" v-if="!over">
      {{ lang.t('components.autoupdate.down', { version }) }}
    </div>
    <div class="version" v-else>
      {{ lang.t('components.autoupdate.ok', { version }) }}
    </div>
    <div class="content">{{ versionContent }}</div>
    <div class="progress"><span class="flash" :style="{ width: progress + '%' }"></span></div>
  </div>
</template>
<script>
import { ref } from 'vue'
import { ipcRenderer } from 'electron'
import app from '@/app'
import { version as getVersion } from '@/api/manage'
import server from '@/api/server'

export default {
  setup() {
    // 完成
    const over = ref(false) 
    // 显示
    const show = ref(false)
    const showOut = ref(false)
    // 版本号
    const version = ref('1.0.0')
    // 版本内容
    const versionContent = ref('')
    // 进度条
    const progress = ref(0)

    ipcRenderer.on('auto-update-down', (event, info) => {
      // 新版本号
      version.value = info.version
      // 加载版本内容
      getVersion().then(res => {
        versionContent.value = res.data[0].content
      })
      onShow()
    })

    ipcRenderer.on('auto-update-progress', (event, pro) => {
      progress.value = pro.percent
    })

    // 更新完成
    ipcRenderer.on('auto-update-ok', () => {
      // 重启 Server
      server.close()
      onShow(true)
    })

    // 显示
    const onShow = (ok) => {
      if(ok) over.value = true
      showOut.value = false
      show.value = true
    }

    // 隐藏
    const onHidden = () => {
      showOut.value = true
      setTimeout(() => show.value = false, 800)
    }

    // 重启
    const onReboot = () => {
      ipcRenderer.send('auto-update-install')
    }

    const start = () => {
      if(process.env.NODE_ENV == 'development') return
      
      // 检查更新
      app.window.update()
    }

    return {
      lang: app.lang,
      over,
      show,
      showOut,
      version,
      versionContent,
      progress,
      onShow,
      onHidden,
      onReboot,
      start
    }
  }
}
</script>